package com.chat.chatgptapi.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

public class ChatConfig {


    public  InputStream postMethod(String param, String urlStr, String keys) {

        //代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                "192.168.0.103", 7890));

        InputStream is = null;
        try {
            byte[] xmlData = param.getBytes("UTF-8");
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url
                    .openConnection(proxy);
            urlCon.setRequestMethod("POST");
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setConnectTimeout(40000);
            urlCon.setReadTimeout(40000);
            urlCon.setRequestProperty("Accept", "application/json");
            urlCon.setRequestProperty("Authorization", "Bearer " + keys);
            urlCon.setRequestProperty("Content-Type", "application/json");
            DataOutputStream printout = new DataOutputStream(
                    urlCon.getOutputStream());
            printout.write(xmlData);

            urlCon.connect();

            int code = urlCon.getResponseCode();
            if (code == 200) {
                is = urlCon.getInputStream(); // 得到网络返回的正确输入流
            } else {
                is = urlCon.getErrorStream(); // 得到网络返回的错误输入流
            }
            printout.flush();
            printout.close();

        } catch (IOException e) {
            System.out.println(e.getMessage());
            is = null;
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            is = null;
            e.printStackTrace();
        }
        return is;
    }

    /**
     * 读取数据。
     */
    public static void readStream(InputStream is, AnsMsgHandler ansMsgHandler) {
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is));
            String line = "";
            while ((line = reader.readLine()) != null) {
                // 处理数据接口
                ansMsgHandler.actMsg(is, line);
            }
            // 当服务器端主动关闭的时候，客户端无法获取到信号。现在还不清楚原因。所以无法执行的此处。
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                throw new IOException("关闭数据流！");
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public interface AnsMsgHandler {
        void actMsg(InputStream is, String line);
    }

}
